#include "Texture.h"

Texture::Texture (QString filename)
{
	QImage img(filename);
	glGenTextures (1,&name);
	glBindTexture (GL_TEXTURE_2D,name);

	// 1E-3 needed. Just try with width=128 and see !
	int newWidth  = 1<<(int)(1+log(img.width() -1+1E-3) / log(2.0));
	int newHeight = 1<<(int)(1+log(img.height()-1+1E-3) / log(2.0));

	if ((img.width()!=newWidth) || (img.height()!=newHeight))
	{
		qWarning("Image size set to %dx%d pixels", newWidth, newHeight);
		img = img.copy(0, 0, newWidth, newHeight);
	}

	QImage glImg = QGLWidget::convertToGLFormat(img);  // flipped 32bit RGBA

	// Bind the img texture...
	glTexImage2D(GL_TEXTURE_2D, 0, 4, glImg.width(), glImg.height(), 0,
		GL_RGBA, GL_UNSIGNED_BYTE, glImg.bits());
}

Texture::~Texture()
{
	glDeleteTextures (1,&name);
}


void Texture::bind (int modulate)
{
	glBindTexture (GL_TEXTURE_2D,name);
	glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
		modulate ? GL_MODULATE : GL_DECAL);
}